# search/views.py
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import status

from management.middleware import skip_middleware_user_activity
from problems.models import Problem
from problems.serializers import ProblemSerializer
from django.core.paginator import Paginator

from utils.logging_utils import log_request_response


@api_view(['GET'])
@skip_middleware_user_activity
@log_request_response
def Problem_Search(request):
    difficulty = request.GET.get('difficulty', None)
    tag = request.GET.get('tag', None)
    keyword = request.GET.get('keyword', None)

    queryset = Problem.objects.all()

    # 根据难度筛选
    if difficulty:
        queryset = queryset.filter(difficulty=difficulty)
    # 根据标签筛选
    if tag:
        queryset = queryset.filter(tags__index=tag)

    if keyword:
        queryset = queryset.filter(problem_name__icontains=keyword)

    page = request.GET.get('page', 1)
    page_size = request.GET.get('page_size', 40)
    paginator = Paginator(queryset, page_size)
    current_page = paginator.page(page)

    serializer = ProblemSerializer(current_page, many=True)

    return Response({
        'page': int(page),
        'page_size': int(page_size),
        'total_pages': paginator.num_pages,
        'total_problems': paginator.count,
        'problems': serializer.data
    })
from django.db.models import Q

@api_view(['GET'])
@skip_middleware_user_activity
@log_request_response
def Problem_Search_All(request):
    difficulty = request.GET.get('difficulty', None)
    tag = request.GET.get('tag', None)
    keyword = request.GET.get('keyword', None)

    queryset = Problem.objects.all()

    # 根据难度筛选
    if difficulty:
        queryset = queryset.filter(difficulty=difficulty)

    # 根据标签筛选
    if tag:
        # 拆分标签字符串并去掉多余空格
        tags = [t.strip() for t in tag.split(',')]
        queryset = queryset.filter(tags__index__in=tags)  # 使用__in进行筛选

    # 根据关键字筛选
    if keyword:
        queryset = queryset.filter(problem_name__icontains=keyword)

    # 序列化查询集
    serializer = ProblemSerializer(queryset, many=True)

    return Response({
        'num': len(serializer.data),
        'problems': serializer.data  # 返回序列化后的数据
    })

